<template>
  <ul class="alphabet-wrapper">
    <li @touchstart="handleTouchStart" @touchend="handleTouchEnd" @touchmove="handleTouchMove" @click="handleClick" class="alphabet-wrapper__item" v-for="item of letters" :key="item" :ref="item">{{item}}</li>
  </ul>
</template>

<script type="text/ecmascript-6">
export default {
  name: 'Alphabet',
  props: {
    cities: Object
  },
  data () {
    return {
      startY: 0,
      touchStatus: false,
      timer: null
    }
  },
  computed: {
    letters () {
      const letters = []
      for (let i in this.cities) {
        letters.push(i)
      }
      return letters
    }
  },
  updated () {
    this.startY = this.$refs['A'][0].offsetTop
  },
  methods: {
    handleClick (e) {
      this.$emit('change', e.target.innerHTML)
    },
    handleTouchStart () {
      this.touchStatus = true
    },
    handleTouchMove (e) {
      if (this.touchStatus) {
        if (this.timer) {
          clearTimeout(this.timer)
        }
        this.timer = setTimeout(() => {
          const touchY = Math.floor(e.touches[0].clientY)
          const index = Math.floor((touchY - this.startY - 75) / 20)
          if (index >= 0 && index < this.letters.length) {
            this.$emit('change', this.letters[index])
            console.log(index)
          }
        }, 16)
      }
    },
    handleTouchEnd () {
      this.touchStatus = false
    }
  }
}
</script>

<style lang="scss" scoped>
  @import "~styles/scss/variable.scss";
  .alphabet-wrapper {
    display: flex;
    flex-direction: column;
    justify-content: center;
    position: absolute;
    top: 1.7rem;
    right: 0;
    bottom: 0;
    z-index: 9;
    width: .6rem;
    &__item {
      color: $color-primary;
      font-size: $fontSize-regular;
      text-align: center;
      height: .4rem;
      line-height: .4rem;
    }
  }
</style>
